package com.shfl.servermanage.logic.api;


import com.shfl.servermanage.common.ApiResultSimpleHelper;
import com.shfl.servermanage.common.SystemConstant;
import com.shfl.servermanage.logic.bean.SysAttachment;
import com.shfl.servermanage.logic.constants.CommonConstants;
import com.shfl.servermanage.logic.model.response.AttachmentResponse;
import com.shfl.servermanage.logic.service.SysAttachmentService;
import com.shfl.servermanage.logic.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/file")
@Api(value = "文件服务", description = "文件服务")
public class FileController {

    @Autowired
    private SysAttachmentService sysAttachmentService;

    @PostMapping(value = "/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    public ApiResultSimpleHelper<AttachmentResponse> addSite(
            @RequestParam("file") MultipartFile file,
            @ApiParam(name = "fileType", example = "1", value = "文件类型", required = true)
            @RequestParam(value = "fileType") Integer fileType
    ) throws Exception {
        String fileName = FileUtils.uploadFile(file, CommonConstants.FILE_ADDRESS, fileType);
        SysAttachment sysAttachment = new SysAttachment();
        sysAttachment.setFileSize(file.getSize());
        sysAttachment.setAttachUrl(fileName);
        sysAttachment.setFileName(file.getName());
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isNotEmpty(originalFilename)) {
            sysAttachment.setFileSuffix(originalFilename.substring(originalFilename.lastIndexOf(".")));
        }
        sysAttachmentService.insertSelective(sysAttachment);
        AttachmentResponse attachmentResponse = new AttachmentResponse();
        attachmentResponse.setOriginalFilename(originalFilename);
        attachmentResponse.setId(sysAttachment.getId());
        attachmentResponse.setPath(CommonConstants.FILE_ADDRESS_READ + fileName);
        return new ApiResultSimpleHelper<>(SystemConstant.RE_SUCCESS_CODE, attachmentResponse);
    }


}
